----------------------------------------------------------------------------------
-- Company: BASH Robotics
-- Engineer: Will Rozzo
-- 
-- Create Date:    15:23:10 07/18/2009 
-- Design Name: 
-- Module Name:    Device_Poller - Behavioral 
-- Project Name: 
-- Target Devices: 
-- Tool versions: 
-- Description: 
--
-- Dependencies: 
--
-- Revision: 
-- Revision 0.01 - File Created
-- Additional Comments: 
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

---- Uncomment the following library declaration if instantiating
---- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity Device_Poller is
Port ( 	   currState : in STD_LOGIC_VECTOR( 1 downto 0 ); -- I think we are cool with 4 states for now, can add more later
				clk : in STD_LOGIC;
				rst : in STD_LOGIC;
				inPkt : in  STD_LOGIC_VECTOR(31 downto 0 ); -- Data gathered from I2C Data Handler
				outAddr : out STD_LOGIC_VECTOR( 7 downto 0); -- This is the address to write to the device memory
				outPkt : out STD_LOGIC_VECTOR(31 downto 0)-- Data sending to Device Memory
				); 
end Device_Poller;

architecture Behavioral of Device_Poller is
type StateType is (RD, WR);
signal internalState, NextState: StateType;

signal pollerData : STD_LOGIC_VECTOR(31 downto 0);
signal addrCntr : STD_LOGIC_VECTOR(7 downto 0) := "00000000"; -- keep track of all the devices polled and written

begin

-- Might need a sub state machine that interacts with the I2C driver
-- depending on the state, (fetchData: ask for data from I2C bus) (writeData: write the data from I2C bus to device mem)
--NEED a process that loops through and grabs data from ALL devices and writes the data to the device memory

	-- This should read, write, read, write over and over again
	comb: process(internalState, currState)
	begin
	
	-- If the current state just started
	if currState'event and currState = "11" then
		addrCntr <= "00000000";
	end if;
	
	if currState = "11" then -- Maybe this will be the 4th state?? 
		case internalState is 
				
			when RD =>

				if addrCntr < 256 then
					-- Set up the writes
					outPkt <= pollerData;
					outAddr <= addrCntr;
					NextState <= WR;
				end if;
				
			when WR =>
			
				if addrCntr < 256 then
					-- set up the data needed in read
					pollerData <= inPkt; -- get the packet from I2C data handler
					NextState <= RD;
				end if;
				addrCntr <= addrCntr + 1;
		end case;
	end if;
	end process comb;
	
	-- UPDATE STATE OR RESET
	seq: process(clk, rst)
	begin
		if( rising_edge(clk) and rst = '1' ) then
			internalState <= RD;
			pollerData <= "00000000000000000000000000000000";
		elsif( rising_edge(clk) ) then
			internalState <= NextState;
		end if;
	end process seq;

end Behavioral;

